package com.smarth.zhizulian.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.smarth.zhizulian.R;
import com.smarth.zhizulian.utils.BitmapUtils;
import com.smarth.zhizulian.utils.KumaLog;
import com.smarth.zhizulian.utils.KumaToast;
import com.smarth.zhizulian.view.surfaceview.DrawHandler;
import com.smarth.zhizulian.view.surfaceview.DrawInterface;
import com.smarth.zhizulian.view.surfaceview.DrawThread;
import com.scwang.smartrefresh.layout.util.DensityUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Created by 18865 on 2018/2/2.
 */

public class HongBaoRainView extends SurfaceView implements DrawInterface, SurfaceHolder.Callback {
    private DrawHandler drawHandler;
    private int width;
    private int height;
    private Bitmap bitmapLeft;
    private Bitmap bitmapRight;
    private int bitmapWidth;
    private int bitmapHeight;
    private Bitmap bitmapAddOne;
    private int count = 0;
    private CopyOnWriteArrayList<MoveModel> moveList = new CopyOnWriteArrayList<>();
    private CopyOnWriteArrayList<ScoreModel> scoreList = new CopyOnWriteArrayList<>();
    private SurfaceHolder holder;
    private OnGetHongBao onGetHongBao;

    public HongBaoRainView(Context context) {
        super(context);
        init();
    }

    public HongBaoRainView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public HongBaoRainView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        holder = getHolder();
        setZOrderOnTop(true);
        holder.setFormat(PixelFormat.TRANSLUCENT);
        holder.addCallback(this);
        prepare();
    }

    public void prepare() {
        DrawThread drawThread = new DrawThread();
        drawThread.start();
        drawHandler = new DrawHandler(drawThread.getLooper(), this);
        Bitmap bitmap = BitmapUtils.scaleImage(BitmapFactory.decodeResource(getResources(), R.drawable.hongbaoyu_hongbao2), DensityUtil.dp2px(48.51f), DensityUtil.dp2px(62.72f));
        bitmapWidth = bitmap.getWidth();
        bitmapHeight = bitmap.getHeight();
        bitmapLeft = BitmapUtils.rotateImageWithoutRecycle(bitmap, -15);
        bitmapRight = BitmapUtils.rotateImageWithoutRecycle(bitmap, 15);
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
        }
        bitmapAddOne = BitmapUtils.scaleImage(BitmapFactory.decodeResource(getResources(), R.drawable.hongbaoyu_jia1), DensityUtil.dp2px(38.22f), DensityUtil.dp2px(28.91f));
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        width = getMeasuredWidth();
        height = getMeasuredHeight();
    }

    public void addMoveModel(MoveModel moveModel) {
        moveList.add(moveModel);
    }

    public void start() {
        count = 0;
        moveList.clear();
        for (int i = 0; i < 10; i++) {
            generateModel();
        }
        drawHandler.callStartDraw();
    }

    public void resume() {
        drawHandler.callStartDraw();
    }

    public void pause() {
        drawHandler.callStopDraw();
    }

    public void quit() {
        if (null != drawHandler) {
            drawHandler.removeCallbacksAndMessages(null);
            drawHandler.getLooper().quit();
        }
    }

    @Override
    public void startDraw() {
        Canvas canvas = holder.lockCanvas();
        if (null == canvas) {
            return;
        }
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);

        for (MoveModel moveModel : moveList) {
            canvas.drawBitmap((moveModel.mode == 0 ? bitmapLeft : bitmapRight), moveModel.x, moveModel.y, paint);
            if (moveModel.x > width || moveModel.y > height) {
                resetMoveModel(moveModel);
            } else {
                moveModel.y += moveModel.randomY;
            }
        }

        for (ScoreModel sm : scoreList) {
            if (System.currentTimeMillis() - sm.createTime < 1000) {
                Paint smPaint = new Paint();
                paint.setAntiAlias(true);
                paint.setAlpha(sm.alpha);
                canvas.drawBitmap(bitmapAddOne, sm.x, sm.y, paint);
                sm.y -= getResources().getDisplayMetrics().density * 1f;
                sm.alpha = (int) (255d - (255d / 1000d) * (System.currentTimeMillis() - sm.createTime));
                KumaLog.kuma("" + sm.alpha);
            } else {
                scoreList.remove(sm);
            }
        }
        holder.unlockCanvasAndPost(canvas);
        drawHandler.callStartDraw();
    }

    @Override
    public void stopDraw() {
        drawHandler.removeStartDraw();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getActionMasked();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                checkInRect((int) event.getX(), (int) event.getY());
                break;
        }
        return true;
    }

    /**
     * 是否点击在红包区域
     *
     * @param x
     * @param y
     */
    private void checkInRect(int x, int y) {
        int length = moveList.size();
        for (int i = 0; i < length; i++) {
            MoveModel moveModel = moveList.get(i);
            Rect rect = new Rect((int) moveModel.x, (int) moveModel.y, (int) moveModel.x + bitmapWidth, (int) moveModel.y + bitmapHeight);
            if (moveModel.isReal && rect.contains(x, y)) {
                count++;
                ScoreModel sm = new ScoreModel();
                sm.x = moveModel.x + ((bitmapWidth - bitmapAddOne.getWidth()) / 2);
                sm.y = moveModel.y;
                sm.createTime = System.currentTimeMillis();
                addScoreModel(sm);
                resetMoveModel(moveModel);
//                KumaToast.show(getContext(), "抢到红包");
                if (onGetHongBao != null) {
                    onGetHongBao.onGetHongBao(count);
                }
                break;
            }
        }
    }

    private void resetMoveModel(MoveModel moveModel) {
        Random random = new Random();
        moveModel.x = random.nextInt(11) * (width / 10);
        moveModel.y = 0;
        moveModel.randomY = (random.nextInt(5) + 2) * getResources().getDisplayMetrics().density * 1.4f;
        moveModel.mode = random.nextInt(2);
        moveModel.isReal = random.nextBoolean();
    }

    private void generateModel() {
        Random random = new Random();
        MoveModel moveModel = new MoveModel();
        moveModel.moveId = moveList.size() + 1;
        moveModel.x = random.nextInt(11) * (width / 10);
        moveModel.y = 0;
        moveModel.randomY = (random.nextInt(5) + 2) * getResources().getDisplayMetrics().density * 1.4f;
        moveModel.mode = random.nextInt(2);
        moveModel.isReal = random.nextBoolean();
        moveList.add(moveModel);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
    }

    public class MoveModel {
        public int moveId;
        public float x;
        public float y;
        public float randomX;
        public float randomY;
        public int mode;
        public boolean isReal;
    }

    private void addScoreModel(ScoreModel sm) {
        scoreList.add(sm);
    }

    public class ScoreModel {
        public float x;
        public float y;
        public long createTime;
        public int alpha;
    }

    public interface OnGetHongBao {
        public void onGetHongBao(int count);
    }

    public OnGetHongBao getOnGetHongBao() {
        return onGetHongBao;
    }

    public void setOnGetHongBao(OnGetHongBao onGetHongBao) {
        this.onGetHongBao = onGetHongBao;
    }

    public int getCount() {
        return count;
    }

}
